import { useCallback, useDebugValue, useEffect, useRef } from 'react';

function useSubscribe(value) {
  const subsList = useRef([]).current;

  useEffect(() => {
    subsList.forEach((fn) => fn?.(value));
  }, [value]);

  useDebugValue(value);

  return useCallback((fn) => {
    if (subsList.indexOf(fn) === -1) subsList.push(fn);
    return () => subsList.splice(subsList.indexOf(fn), 1);
  }, []);
}

export default useSubscribe;
